<?php

class Core_LocaleController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $locale = $this -> _getParam('locale');
        $language = $this -> _getParam('language');
        $return = $this -> _getParam('return', $this -> _helper -> url -> url(array(), 'default', true));
        
        $viewer = Nuo::getViewer();

        if (!empty($locale))
        {
            try
            {
                $locale = Zend_Locale::findLocale($locale);
            }
            catch( Exception $e )
            {
                $locale = null;
            }
        }
        if (!empty($language))
        {
            try
            {
                $language = Zend_Locale::findLocale($language);
            }
            catch( Exception $e )
            {
                $language = null;
            }
        }

        if ($language && !$locale)
            $locale = $language;
        if (!$language && $locale)
            $language = $locale;

        if ($language && $locale)
        {
            // Set as cookie
            @setcookie('nuo_language', $language, time() + (86400 * 365), '/');
            @setcookie('nuo_locale', $locale, time() + (86400 * 365), '/');
            // Set as database
            if ($viewer && $viewer -> getIdentity())
            {
                $viewer -> locale = $locale;
                $viewer -> language = $language;
                $viewer -> save();
            }
        }

        return $this -> _helper -> redirector -> gotoUrl($return, array('prependBase' => false));

    }

}
